package com.qf.springwork.service.imlp;

import com.qf.springwork.dao.UserDao;
import com.qf.springwork.entity.User;
import com.qf.springwork.service.UserService;
import com.qf.springwork.utils.UserWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

@Service("userService")
public class UserServiceImlp implements UserService {

    @Autowired
    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void getById(Integer id) {
        User user = userDao.selectById(id);
        System.out.println(user.getName());
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public void addAll() {
        List<User> users = User.randomUsers(10000);
        userDao.insertAll(users);
    }

    @Override
    public void getAll() throws InterruptedException {
        UserWriter userWriter = new UserWriter();
        ExecutorService pool = Executors.newFixedThreadPool(8);
        ReentrantLock lock = new ReentrantLock();
        CountDownLatch latch = new CountDownLatch(14);
        for (int i = 1;i<=14;i++){
            int start = (i-1)*10000;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    List<User> users = userDao.selectAll(start, 10000);
                    lock.lock();
                    userWriter.userAddWriter(users);
                    latch.countDown();
                    lock.unlock();
                }
            });
        }
        latch.await();
    }
}
